<template>
  <div class="index-box">
    <el-container>
      <el-container>
        <!--头部布局-->
        <el-header height="42px" class="header-content-box">
          <div class="logo">Form Builder</div>
          <div class="header-btn-box">
            <el-button icon="el-icon-video-play" type="text" @click="run">运行</el-button>
            <el-button icon="el-icon-view" type="text" @click="showJson">查看json</el-button>
            <el-button icon="el-icon-download" type="text" @click="copy">导出vue文件</el-button>
            <el-button icon="el-icon-delete" type="text" @click="empty">清空</el-button>
          </div>
        </el-header>
        <el-container>
          <el-aside width="260px" class="left-content-box">
            <el-scrollbar>
              <div class="components-list">
                <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
                  <div class="components-title">
                    <svg-icon icon-class="component"/>
                    {{ item.title }}
                  </div>
                  <draggable
                    class="components-draggable"
                    :list="item.list"
                    :group="{ name: 'componentsGroup', pull: 'clone', put: false}"
                    :clone="cloneComponent"
                    draggable=".components-item"
                    :sort="false"
                    @end="onEnd"
                  >
                    <div v-for="(element, index) in item.list"
                         :key="index"
                         class="components-item"
                         @click="addComponent(element)"
                    >
                      <div class="components-body">
                        <svg-icon :icon-class="element.config.tagIcon"/>
                        {{ element.config.label }}
                      </div>
                    </div>
                  </draggable>
                </div>
              </div>
            </el-scrollbar>
          </el-aside>
          <el-container class="center-content-box">
            <el-scrollbar>
              <el-row class="center-board-row" :gutter="formConf.gutter">
                <el-form
                  :size="formConf.size"
                  :label-position="formConf.labelPosition"
                  :disabled="formConf.disabled"
                  :label-width="formConf.labelWidth+'px'"
                >
                  <draggable
                    class="drawing-board"
                    :list="drawingList"
                    :animation="340"
                    group="componentsGroup"
                  >
                    <draggable-item
                      v-for="(item, index) in drawingList"
                      :key="item.renderKey"
                      :drawing-list="drawingList"
                      :current-item="item"
                      :index="index"
                      :active-id="activeId"
                      :form-conf="formConf"
                      @activeItem="activeFormItem"
                      @copyItem="drawingItemCopy"
                      @deleteItem="drawingItemDelete"
                    ></draggable-item>
                  </draggable>
                  <div v-show="!drawingList.length" class="empty-info">
                    从左侧拖入或点击组件进行表单设计
                  </div>
                </el-form>
              </el-row>
            </el-scrollbar>
          </el-container>
        </el-container>
      </el-container>
      <el-aside class="right-content-box" width="350px">
        <right-panel :active-data="activeData"
                     :form-conf="formConf"
                     :show-field="!!drawingList.length"
                     @tag-change="tagChange"
                     @fetch-data="fetchData"></right-panel>
      </el-aside>
    </el-container>
    <form-drawer :visible.sync="drawerVisible" :form-data="formData" size="100%" :generate-conf="generateConf"></form-drawer>
    <code-type-dialog :visible.sync="dialogVisible" title="选择生成类型"
                      :show-file-name="showFileName" @confirm="generate"></code-type-dialog>
    <json-drawer size="60%" :visible.sync="jsonDrawerVisible" :json-str="JSON.stringify(formData)" @refresh="refreshJson"></json-drawer>
    <input id="copyNode" type="hidden">
  </div>
</template>

<script>
import { formConf, inputComponents, selectComponents, layoutComponents } from '@/components/generator/config'
import draggable from 'vuedraggable'
import drawingDefault from '@/components/generator/drawingDefault'
import DraggableItem from '@/components/draggableItem/draggableItem'
import { beautifierConf, deepClone, isObjectObject, titleCase } from '@/utils'
import { getDrawingList, getFormConf, getIdGlobal, saveDrawingList, saveIdGlobal } from '@/utils/setLocal'
import { debounce } from 'throttle-debounce'
import loadBeautifier from '@/utils/loadBeautifier'
import ClipboardJS from 'clipboard'
import RightPanel from '@/views/RightPanel'
import CodeTypeDialog from '@/views/CodeTypeDialog'
import FormDrawer from '@/views/FormDrawer'
import JsonDrawer from '@/views/JsonDrawer'
import { saveAs } from 'file-saver'
import { cssStyle, makeUpHtml, vueScript, vueTemplate } from '@/components/generator/html'
import { makeUpJs } from '@/components/generator/js'
import { makeUpCss } from '@/components/generator/css'

// eslint-disable-next-line no-unused-vars
let beautifier
// eslint-disable-next-line no-unused-vars
const emptyActiveData = { style: {}, autosize: {} }
// eslint-disable-next-line no-unused-vars
let oldActiveId, tempActiveData
const drawingListLocal = getDrawingList()
const formConfLocal = getFormConf()
const idGlobal = getIdGlobal()

export default {
  name: 'index',
  components: {
    JsonDrawer,
    FormDrawer,
    CodeTypeDialog,
    RightPanel,
    inputComponents,
    selectComponents,
    layoutComponents,
    draggable,
    DraggableItem
  },
  data () {
    return {
      idGlobal,
      formConf,
      leftComponents: [
        {
          title: '输入型组件',
          list: inputComponents
        },
        {
          title: '选择型组件',
          list: selectComponents
        },
        {
          title: '布局型组件',
          list: layoutComponents
        }
      ],
      inputComponents,
      selectComponents,
      layoutComponents,
      labelWidth: 100,
      drawingList: drawingDefault,
      drawingDta: {},
      activeId: drawingDefault[0].formId,
      activeData: drawingDefault[0],
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      jsonDrawerVisible: false,
      generateConf: null,
      showFileName: false,
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal)
    }
  },
  watch: {
    'activeData.config.label' (val, oldVal) {
      if (this.activeData.placeholder === undefined || !this.activeData.config.tag || oldActiveId !== this.activeId) {
        return
      }
      this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
    },
    activeId: {
      handler (val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler (val) {
        this.saveDrawingListDebounce(val)
        if (val.length === 0) this.idGlobal = 100
      },
      deep: true
    },
    idGlobal: {
      handler (val) {
        this.saveIdGlobalDebounce(val)
      },
      immediate: true
    }
  },
  mounted () {
    if (Array.isArray(drawingListLocal) && drawingListLocal.length > 0) {
      this.drawingList = drawingListLocal
    } else {
      this.drawingList = drawingDefault
    }
    this.activeFormItem(this.drawingList[0])
    if (formConfLocal) {
      this.formConf = formConfLocal
    }
    loadBeautifier(btf => {
      beautifier = btf
    })
    const clipboard = new ClipboardJS('#copyNode', {
      text: trigger => {
        const codeStr = this.generateCode()
        this.$notify({
          title: '成功',
          message: '代码已复制到剪切板，可粘贴。',
          type: 'success'
        })
        return codeStr
      }
    })
    clipboard.on('error', e => {
      this.$message.error('代码复制失败')
    })
  },
  methods: {
    setObjectValueReduce (obj, strKeys, data) {
      const arr = strKeys.split('.')
      arr.reduce((pre, item, i) => {
        if (arr.length === i + 1) {
          pre[item] = data
        } else if (!isObjectObject(pre[item])) {
          pre[item] = {}
        }
        return pre[item]
      }, obj)
    },
    setRespData (component, resp) {
      const { dataPath, renderKey, dataConsumer } = component.config
      if (!dataPath || !dataConsumer) return
      // 解析 responseData
      const respData = dataPath.split('.').reduce((prev, item) => prev[item], resp)
      this.setObjectValueReduce(component, dataConsumer, respData)
      const i = this.drawingList.findIndex(item => item.config.renderKey === renderKey)
      if (i > -1) this.$set(this.drawingList, i, component)
    },
    setLoading (component, val) {
      const { directives } = component
      if (Array.isArray(directives)) {
        const t = directives.find(d => d.name === 'loading')
        if (t) t.value = val
      }
    },
    fetchData (component) {
      const { dataType, method, url } = component.config
      if (dataType === 'dynamic' && method && url) {
        this.setLoading(component, true)
        this.$axios({
          method,
          url
        }).then(resp => {
          this.setLoading(component, false)
          this.setRespData(component, resp.data)
        })
      }
    },
    activeFormItem (currentItem) {
      this.activeData = currentItem
      this.activeId = currentItem.config.formId
    },
    createIdAndKey (item) {
      const config = item.config
      config.formId = ++this.idGlobal
      config.renderKey = `${config.formId}${+new Date()}`
      if (config.layout === 'colFormItem') {
        item.vModel = `field${this.idGlobal}`
      } else if (config.layout === 'rowFormItem') {
        config.componentName = `row${this.idGlobal}`
        !Array.isArray(config.children) && (config.children = [])
        delete config.label
      }
      if (Array.isArray(config.children)) {
        config.children = config.children.map(childItem => this.createIdAndKey(childItem))
      }
      return item
    },
    cloneComponent (origin) {
      const clone = deepClone(origin)
      const config = clone.config
      config.span = this.formConf.span
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config.label)
      tempActiveData = clone
      return tempActiveData
    },
    addComponent (item) {
      const clone = this.cloneComponent(item)
      this.fetchData(clone)
      this.drawingList.push(clone)
      this.activeFormItem(clone)
    },
    onEnd (obj) {
      if (obj.from !== obj.to) {
        this.fetchData(tempActiveData)
        this.activeData = tempActiveData
        this.activeId = this.idGlobal
      }
    },
    drawingItemCopy (item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      list.push(clone)
      this.activeFormItem(clone)
    },
    drawingItemDelete (index, list) {
      list.splice(index, 1)
      this.$nextTick(() => {
        const len = this.drawingList.length
        if (len) {
          this.activeFormItem(this.drawingList[len - 1])
        }
      })
    },
    generateCode () {
      const { type } = this.generateConf
      this.AssembleFormData()
      const script = vueScript(makeUpJs(this.formData, type))
      const html = vueTemplate(makeUpHtml(this.formData, type))
      const css = cssStyle(makeUpCss(this.formData))
      return beautifier.html(html + script + css, beautifierConf.html)
    },
    tagChange (newTag) {
      newTag = this.cloneComponent(newTag)
      const config = newTag.config
      newTag.vModel = this.activeData.vModel
      config.formId = this.activeId
      config.span = this.activeData.config.span
      this.activeData.config.tag = config.tag
      this.activeData.config.tagIcon = config.tagIcon
      this.activeData.config.document = config.document
      if (typeof this.activeData.config.defaultValue === typeof config.defaultValue) {
        config.defaultValue = this.activeData.config.defaultValue
      }
      Object.keys(newTag).forEach(key => {
        if (this.activeData[key] !== undefined) {
          newTag[key] = this.activeData[key]
        }
      })
      this.activeData = newTag
      this.updateDrawingList(newTag, this.drawingList)
    },
    updateDrawingList (newTag, list) {
      const index = list.findIndex(item => item.config.formId === this.activeId)
      if (index > -1) {
        list.splice(index, 1, newTag)
      } else {
        list.forEach(item => {
          if (Array.isArray(item.config.children)) {
            this.updateDrawingList(newTag, item.config.children)
          }
        })
      }
    },
    run () {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'run'
    },
    generate (data) {
      const func = this[`exec${titleCase(this.operationType)}`]
      this.generateConf = data
      func && func(data)
    },
    AssembleFormData () {
      this.formData = {
        fields: deepClone(this.drawingList),
        ...this.formConf
      }
    },
    refreshJson (data) {
      this.drawingList = deepClone(data.fields)
      delete data.fields
      this.formConf = data
    },
    showJson () {
      this.AssembleFormData()
      this.jsonDrawerVisible = true
    },
    downLoad () {
      this.dialogVisible = true
      this.showFileName = true
      this.operationType = 'download'
    },
    copy () {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'copy'
    },
    empty () {
      this.$confirm('确定要清空所有组件吗?', '提示', { type: 'warning' }).then(() => {
        this.drawingList = []
        this.idGlobal = 100
      })
    },
    execRun () {
      this.AssembleFormData()
      this.drawerVisible = true
    },
    execDownload (data) {
      const codeStr = this.generateCode()
      const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
      saveAs(blob, data.fileName)
    },
    execCopy () {
      document.getElementById('copyNode').click()
    }
  }

}
</script>

<style lang="less">
@import "@/style/index.less";
</style>
